#include "microgridsystem.h"
#include "scheduler.h"
#include <QDebug>

MicrogridSystem::MicrogridSystem(QObject *parent) : QObject(parent) {
    // 初始化代码
}

void MicrogridSystem::addComponent(Component* component) {
    if (!component) return;

    auto sharedComp = std::shared_ptr<Component>(component);
    m_components.append(sharedComp);
}

QVector<Component*> MicrogridSystem::getComponents() const {
    QVector<Component*> result;
    for (const auto& comp : m_components) {
        result.append(comp.get());
    }
    return result;
}

void MicrogridSystem::runSimulation() {
    const int totalSteps = 96;
    const double dt = 0.25;

    // 重置历史数据
    m_powerHistory.clear();

    for (m_currentTimeStep = 0; m_currentTimeStep < totalSteps; m_currentTimeStep++) {
        // 更新所有组件状态
        for (const auto& comp : m_components) {
            comp->update(m_currentTimeStep, dt);
            m_powerHistory[comp->getName()].append(comp->getPower());
        }

        // 修复引用传递问题
        QVector<Component*> currentComponents;
        for (const auto& comp : m_components) {
            currentComponents.append(comp.get());
        }
        Scheduler::dispatch(currentComponents, dt, m_currentTimeStep);
    }

    emit simulationFinished();
}

QVector<double> MicrogridSystem::getPowerHistory(const QString& componentName) const {
    return m_powerHistory.value(componentName);
}
